<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>理解观察者模式</title>
</head>
<body>
    <script>
        function show(data) {
            console.log('data :>> ', data);
        }

        var Observe = {
            callbacks: [],
            add: function(fn) {
                this.callbacks.push(fn)
            },
            fire: function(data) {
                this.callbacks.forEach(function(task) {
                    task(data)
                })
            }
        }

        Observe.add(function() {
            show('add1')
        })
        Observe.add(function() {
            show('add2')
        })
        Observe.fire()


        // 发布订阅模式实际应用
        function mAjax(arg) {
            setTimeout(function () {
                arg.success(arg.data+'收到返回的数据！')
            }, 1000);
        }
        Observe.add(function(data) {
            // eg: 处理ajax返回数据
            show(data+'ajax-handler1')
        })
        Observe.add(function(data) {
            // eg: 渲染dom
            show(data+'ajax-handler2')
        })
        mAjax({
            data: '数据',
            success: function(res) {
                Observe.fire(res)
            }
        })
    </script>
</body>
</html>